package org.whatever.aha.zjut.platform.controller.project;

import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.annotation.SaMode;
import cn.dev33.satoken.stp.StpUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.whatever.aha.zjut.base.constant.AuthConst;
import org.whatever.aha.zjut.base.constant.ErrorCode;
import org.whatever.aha.zjut.base.constant.MsgTypeRedisConstant;
import org.whatever.aha.zjut.base.constant.StatusConstant;
import org.whatever.aha.zjut.base.dto.AjaxResult;
import org.whatever.aha.zjut.base.exception.AppException;
import org.whatever.aha.zjut.platform.annotation.ProjectPermission;
import org.whatever.aha.zjut.platform.annotation.StageLimit;
import org.whatever.aha.zjut.platform.entity.competition.CompetitionStageStatus;
import org.whatever.aha.zjut.platform.entity.project.Project;
import org.whatever.aha.zjut.platform.message.MessageService;
import org.whatever.aha.zjut.platform.service.AcademyAdminService;
import org.whatever.aha.zjut.platform.service.competition.CompetitionService;
import org.whatever.aha.zjut.platform.service.competition.CompetitionStageStatusService;
import org.whatever.aha.zjut.platform.service.project.ProjectAppJudgeService;
import org.whatever.aha.zjut.platform.service.project.ProjectService;
import org.whatever.aha.zjut.platform.service.school.ProjectScoreService;
import org.whatever.aha.zjut.platform.util.CheckUtil;
import org.whatever.aha.zjut.platform.vo.PageVo;
import org.whatever.aha.zjut.platform.vo.project.ProjectAppJudgeVo;
import org.whatever.aha.zjut.platform.vo.project.ProjectJudgeAppResultVo;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;

/**
 * @author Vc, Elder Master
 * @version 1.0
 * @Desc
 * @date 2021/11/12 8:02 下午
 */

@Api(tags="评委申请意见相关请求")
@RequestMapping("v1/projectAppJudge")
@RequiredArgsConstructor
@RestController
@Validated
public class ProjectAppJudgeController {

    final ProjectAppJudgeService projectAppJudgeService;
    final ProjectService projectService;
    final CompetitionService competitionService;
    final CompetitionStageStatusService competitionStageStatusService;
    final ProjectScoreService projectScoreService;
    final MessageService messageService;
    final AcademyAdminService academyAdminService;

    /**
     * 分页条件查询当前用户申请评委意见审批结果
     *
     * @param applyStatus
     * @param pageNum
     * @param pageSize
     * @return
     */
    @ApiOperation(value = "分页条件查询当前用户申请评委意见审批结果")
    @GetMapping("/getProjectAppJudge")
    AjaxResult<PageVo<List<ProjectAppJudgeVo>>> getProjectAppJudgePagable(@RequestParam(value = "applyStatus", required = false)Integer applyStatus,
                                                                          @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                                                                          @RequestParam(value = "pageSize", defaultValue = "10") int pageSize){
        int userId = StpUtil.getLoginIdAsInt();
        List<Object> projectIds = projectService.getProjectIdsByLeaderId(userId);
        return AjaxResult.SUCCESS(projectAppJudgeService.getProjectAppJudgePagable(projectIds, applyStatus, pageNum, pageSize));
    }

    /**
     * 院级管理员分页条件查询当前用户申请评委意见审批结果
     *
     * @param applyStatus
     * @param pageNum
     * @param pageSize
     * @return
     */
    @SaCheckRole(value = {AuthConst.R_academy, AuthConst.R_supper}, mode = SaMode.OR)
    @ApiOperation(value = "分页条件查询当前用户申请评委意见审批结果")
    @GetMapping("/getProjectAppJudgeAcademy")
    AjaxResult<PageVo<List<ProjectAppJudgeVo>>> getProjectAppJudgePagableAcademy(@RequestParam(value = "applyStatus", required = false)Integer applyStatus,
                                                                          @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                                                                          @RequestParam(value = "pageSize", defaultValue = "10") int pageSize){
        int userId = StpUtil.getLoginIdAsInt();
        int academyId = academyAdminService.getAcademyIdByUserId(userId);
        List<Object> projectIds = projectService.getProjectIdsByAcademyId(academyId);
        return AjaxResult.SUCCESS(projectAppJudgeService.getProjectAppJudgePagable(projectIds, applyStatus, pageNum, pageSize));
    }

    /**
     * 新增申请，只有公示阶段可申请，同一个项目只能提交一次申请
     *
     * @param projectId
     * @return
     */
    @ApiOperation(value = "新增申请", notes = "只有公示阶段可申请，同一个项目只能提交一次申请")
    @StageLimit({"public"})
    @ProjectPermission
    @PostMapping("/addProjectAppJudge/{projectId}/{stageId}")
    AjaxResult<Integer> addProjectAppJudge(@PathVariable("projectId") int projectId, @PathVariable("stageId")int stageId){
        return AjaxResult.SUCCESS(projectAppJudgeService.addProjectAppJudge(projectId));
    }


    /**
     * 审核申请
     *
     * @param projectId
     * @param applyStatus
     * @param applyComment
     * @return
     */
    @ApiOperation(value = "审核申请", notes = "只有院级管理员、超管可以操作")
    @SaCheckRole(value = {AuthConst.R_academy, AuthConst.R_supper}, mode = SaMode.OR)
    @PutMapping("/approveProjectAppJudge")
    @Transactional(rollbackFor = Exception.class, propagation= Propagation.REQUIRED)
    AjaxResult<Integer> approveProjectAppJudge(@RequestParam("projectId") int projectId, @RequestParam("applyStatus") int applyStatus, @RequestParam(value = "applyComment", required = false) String applyComment){
        Integer affectRow = projectAppJudgeService.approveProjectAppJudge(projectId, applyStatus, applyComment);
        SimpleDateFormat s=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String sendTime = s.format(Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTime());
        messageService.createUserMessage(StatusConstant.MSG_SYS_SENDER.getCode(), projectId, sendTime,
                MsgTypeRedisConstant.MSG_TYPE_APP_JUDGE_TITLE, MsgTypeRedisConstant.getKeyAppJudge(projectService.getProjectNameById(projectId), "院级管理员", applyStatus == 3 ? "通过" : "拒绝", applyComment == null ? "" : applyComment),
                MsgTypeRedisConstant.MSG_SYS_NAME, StatusConstant.MSG_TYPE_APP_JUDGE.getCode());
        return AjaxResult.SUCCESS(affectRow);
    }

    /**
     * 根据申请项目id对查询进行撤回/删除
     *
     * @param projectId
     * @return
     */
    @ProjectPermission
    @ApiOperation("根据申请项目id对查询进行撤回/删除")
    @DeleteMapping("/withdrawProjectAppJudge/{projectId}")
    AjaxResult<Integer> withdrawProjectAppJudge(@PathVariable("projectId") int projectId){
        //提交阶段 && 项目未提交
        CompetitionStageStatus singleCompStageStatus = competitionStageStatusService.getSingleCompStageStatus(projectService.getProjectDetailById(projectId).getStageId(), StatusConstant.COMPETITION_STAGE_STATUS_ORDER_SUBMIT.getCode());
        CheckUtil.checkTimeLimit(singleCompStageStatus.getStatusStartTime(), singleCompStageStatus.getStatusEndTime());
        CheckUtil.checkStuStatus(StatusConstant.PROJECT_STUDENT_STATUS_WAIT_FOR_SUBMIT.getCode(), projectService.getProjectStuStatus(projectId));

        return AjaxResult.SUCCESS(projectAppJudgeService.withdrawProjectAppJudge(projectId));
    }

    /**
     * 查询评委评审结果
     *
     * @param projectId
     * @return
     */
    @ApiOperation("查询评委评审结果")
    @ProjectPermission
    @GetMapping("/getJudgeResult/{projectId}")
    AjaxResult<List<ProjectJudgeAppResultVo>> getJudgeResult(@PathVariable("projectId") int projectId){
        if(!StatusConstant.COMPETITION_APP_JUDGE_STATUS_ALLOW.getCode().equals(projectAppJudgeService.getApplyStatusByProjectId(projectId))){
            throw new AppException(ErrorCode.PROJECT_APP_NOT_ALLOW);
        }
        return AjaxResult.SUCCESS(projectScoreService.getJudgeResultStu(projectId));
    }

}